<template>
  <div>
    <el-button type="primary" @click="getMenus">刷新数据</el-button>
    <el-button type="primary" @click="addRootCategory">添加根种类</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽">
    </el-switch>
    <el-button v-if="draggable" type="primary" @click="submitDrag">保存修改</el-button>
    <el-button v-if="draggable" type="primary" @click="cancelDrag">取消拖拽</el-button>

    <el-tree
      ref="infoCateTree"
      :data="data"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expandedKeys"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-click="handlerNodeClick"
      @node-drop="handlerNodeDrop"
      ><span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level != 3"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="update(data)"
          >
            Update
          </el-button>
        </span>
      </span>
    </el-tree>

    <!-- Form -->

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form :model="category">
        <el-form-item label="分类名称" :label-width="formLabelWidth">
          <el-input v-model="category.catName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCategory">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      data: [],
      defaultProps: {
        label: "catName",
        children: "children",
      },
      expandedKeys: [],

      dialogType: "",
      dialogVisible: false,
      formLabelWidth: "80px",
      dialogTitle: "",
      category: {
        catId: null,
        catName: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 1,
      },

      draggable: false,
      dragNodes: [],
      pCid: [],
    };
  },
  methods: {
    

    /**
     * 从后端获取 树形数据集合
     */
    getMenus() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/admin/info/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        // console.log("成功获取到数据");
        console.log("从后端获取数据成功：", data);
        this.data = data.data;
      });
      this.expandedKeys = []
    },

    batchDelete(){
      var checkedNodes = this.$refs.infoCateTree.getCheckedNodes(false, false);
      console.log("被选中的节点", checkedNodes);
      var deleteIds = [];
      for(var i = 0;i<checkedNodes.length;i++){
        deleteIds.push(checkedNodes[i].catId);
      }

      this.$confirm(`是否批量删除[${deleteIds}]`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
      .then(() => {
        // 确定，发送请求
        this.$http({
          url: this.$http.adornUrl("/admin/info/category/delete"),
          method: "post",
          data: this.$http.adornData(deleteIds, false)
        }).then(({ data }) => {
          this.$message({
            type: "success",
            message: "成功!",
          });
          this.getMenus();
        });
      })
      .catch(() => {

      });

      
    },

    /**
     * 确定 or 取消拖拽
     */
    submitDrag(){
      // 发送请求，完成修改，并清空 dragNods
      this.$http({
        url: this.$http.adornUrl("/admin/info/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.dragNodes, false)
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "修改成功!",
        });
        this.dragNodes = []
        this.getMenus();
        this.expandedKeys = this.pCid
        this.pCid = [];
      });
    },
    cancelDrag(){
      this.getMenus()
      this.draggable = false;
      this.dragNodes = [];
    },

    /**
     * 进行拖拽时，判断节点能否被放置在某个位置上
     * 参数：被拖拽节点，放置在某个节点，某个位置
     */
    allowDrop(draggingNode, dropNode, type){
      
      // console.log("进行拖拽：",draggingNode, dropNode, type);
      // 计算两个层级的和，保证其 <= 3
      var sum1 = 0;
      var sum2 = this.calcDepth(draggingNode);
      if(type === 'inner'){
        sum1 = dropNode.level;
      }else{
        sum1 = dropNode.level - 1;
      }
      // console.log("二者的层级：", sum1, sum2, (sum1 + sum2))
      if((sum1 + sum2) <= 3){
        return true;
      }
      return false;
    },

    /**
     * 计算某个节点的最大深度
     */
    calcDepth(node){
      var depth = 0;
      if(node.childNodes == null || node.childNodes.length == 0){
        return 1;
      }
      for(var i = 0;i<node.childNodes.length;i++){
        depth = Math.max(depth, this.calcDepth(node.childNodes[i]) + 1);
      }
      return depth;
    },
    
    handlerNodeClick(data, node){
      console.log("当前节点的深度", this.calcDepth(node), node)
    },

    /**
     * 拖拽功能 影响节点的属性：父id、层级、排序
     *    提交内容：catId、parentCid、catLevel、sort
     * 什么时候需要考虑子节点：父id、排序 不用考虑，层级仅在父的层级发生变换时考虑。
     */
    handlerNodeDrop(draggingNode, dropNode, type){
      console.log("成功拖拽", draggingNode, dropNode, type);
      var parentCid;
      var catLevel;
      var sort;
      var sortNodes;
      if(type == 'inner'){
        parentCid = dropNode.data.catId;
        catLevel = dropNode.data.catLevel + 1;
        sortNodes = dropNode.childNodes;
      }else{
        catLevel = dropNode.data.catLevel;
        
        if(catLevel === 1){
          parentCid = 0
        }else{
          parentCid = dropNode.parent.data.catId;
        }
        sortNodes = dropNode.parent.childNodes;

      }
      this.pCid.push(parentCid);

      

      // 顺序sort
      console.log("需要排序的所有节点", sortNodes);

      for(var i = 0;i<sortNodes.length;i++){
        if(sortNodes[i].data.catId == draggingNode.data.catId){
          if(catLevel != draggingNode.data.catLevel){
            // 子节点的 层级 也需要修改
            this.dragNodes.push({catId:sortNodes[i].data.catId, catLevel: catLevel, parentCid: parentCid, sort: i})
            this.colloctChildLevel(sortNodes[i])
          }else{
            this.dragNodes.push({catId:sortNodes[i].data.catId, parentCid: parentCid, sort: i})
          }
          
        }else{
          this.dragNodes.push({catId:sortNodes[i].data.catId, sort: i})
        }
      }
      console.log("需要修改的所有节点信息，进行提交", this.dragNodes);

      
    },

    /**
     * 收集子节点的最新层级信息
     */
    colloctChildLevel(node){
      if(node.childNodes == null || node.childNodes.length == 0){
        return; 
      }  
      for(var i = 0;i < node.childNodes.length;i++){
        this.dragNodes.push({
          catId: node.childNodes[i].data.catId,
          catLevel: node.childNodes[i].level,
        })
        this.colloctChildLevel(node.childNodes[i]);
      }
    },

    addRootCategory(){
      this.dialogTitle = "添加根分类";
      this.dialogType = 'append';

      this.category.catName = "";
      this.category.parentCid = 0;
      this.category.catLevel = 1;
      this.category.showStatus = 1;
      this.category.sort = 0;

      this.dialogVisible = true;

    },

    /**
     * 打开 添加三级分类对话框
     */
    append(data) {
      this.dialogTitle = "添加分类";
      this.dialogType = "append";

      this.category.catName = "";
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      this.category.showStatus = 1;
      this.category.sort = 1;

      this.dialogVisible = true;
      console.log("data", data);
    },

    /**
     * 发送请求，添加三级分类
     *  */
    addCategory() {
      console.log("添加名称", this.category);
      this.$http({
        url: this.$http.adornUrl("/admin/info/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "添加成功!",
        });
        this.getMenus();
        this.expandedKeys = [this.category.parentCid];
      });
    },

    /**
     * 根据 dialogTpye 的值，进行 添加 或 修改 操作
     */
    submitCategory(){
      if(this.dialogType == "append"){
        this.addCategory();
      }else if(this.dialogType == "update"){
        this.updateCategory();
        this.category.catId = null;
      }
      this.dialogVisible = false;
      
      // this.getMenus(); // 这里因为是异步修改，所以可能没有修改，就获取了数据
    },

    updateCategory(){
      var {catId, catName} = this.category;
      this.$http({
        url: this.$http.adornUrl("/admin/info/category/update"),
        method: "post",
        data: this.$http.adornData({catId, catName}, false)
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "修改成功!",
        });
        this.getMenus(); // 这里的 this 是我要的this
        this.expandedKeys = [this.category.parentCid];
      });
    },

    /**
     * 修改三级分类
     *
     */
    update(data) {
      console.log("update", data);
      this.dialogTitle = "修改分类";
      this.dialogType = 'update';

      this.category.catId = data.catId;
      this.category.catName = data.catName;
      this.category.parentCid = data.parentCid;

      this.dialogVisible = true;
    },

    /**
     * 删除：node 中包含一个 data
     *  */
    remove(node, data) {
      this.$confirm(`是否删除信息种类[${data.catName}]`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var ids = [data.catId];
          this.$http({
            url: this.$http.adornUrl("/admin/info/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });

            this.getMenus();

            // 设置需要默认展开的菜单
            this.expandedKeys = [node.parent.data.catId];
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      console.log("node", node, "data", data);
    },
  },
  created() {
    this.getMenus();
  },
};
</script>

<style>
</style>